﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CMS.Entity;
using CMS.BLL;
using System.Text.RegularExpressions;
using System.Drawing;
using CMS.Common;
using UserCenter.Common;

public partial class Partners_add :Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            BindType();
            int pid = 0;
            if (Request["PId"] != null && Request["PId"].ToString() != "")
            {
                pid = int.Parse(Request["PId"].ToString());
            }
            BindData(pid);
            
        }
    }

    protected void BindType()
    {
        CMSModel.CMSEntities dal = DAL.DBManager.GetCmsEmtity();        
        //先获取父id、
        string pid = "";
        if (dal.NewsType.Where(x => x.name == "合作伙伴").ToArray().Length > 0)
            pid = dal.NewsType.Where(x => x.name == "合作伙伴").Select(x => x.id).First();
        else
        {
            ClientScript.RegisterClientScriptBlock(GetType(), "aa", "alert('暂无合作伙伴类别，请至新闻类型中添加！',document.location='default.aspx');", true);
            return;
        }            
        //string pid = System.Configuration.ConfigurationManager.AppSettings["PartnerTypeId"].ToString();
        ddlPid.DataSource = dal.NewsType.Where(x => x.pid == pid).Select(x => new { x.id, x.name }).ToArray();

        ddlPid.DataValueField = "id";
        ddlPid.DataTextField = "name";
        ddlPid.DataBind();
        ddlPid.Items.Insert(0, new ListItem("--请选择类别--", ""));
    }


    protected void BindData(int pid)
    {
        if (pid > 0)
        {
            //说明是修改
            PartnerBLL bll = new PartnerBLL();
            PartnerEnty partner = bll.GetOne(pid);
            if (partner.Ppicture != null && partner.Ppicture.ToString() != "")
            {
                Image1.Visible = true;
                Image1.ImageUrl = partner.Ppicture;
            }
            else
                Image1.Visible = false;
           
            txtTitle.Text = partner.Pname;
            txtTime.Text = string.Format("{0:yyyy-MM-dd HH:mm}", partner.CreateTime);
            txtPhone.Text = partner.Pphone;
            txtOutsideUrl.Text = partner.Purl;
            txtEMail.Text = partner.Pemail;
            txtContent.Text = partner.Pdes;
            txtPX.Text = partner.SortNum.ToString();
            ddlPid.SelectedValue = partner.Padr == "" || partner.Padr == null ? "" : partner.Padr;
            if (partner.Status == true)
                rdoEnableYes.Checked = true;
            else
                rdoEnableNo.Checked = true;

        }
        else
        {
            //说明是新增
            Image1.Visible = false;
        }
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx?page=" + Request["page"]);
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        int pid = 0;
        try
        {
            PartnerEnty pt = new PartnerEnty();
            //保存
            PartnerBLL bll = new PartnerBLL();
            
            if (Request["PId"] != null && !string.IsNullOrEmpty(Request["PId"]))
            {
                pid = int.Parse(Request["Pid"]);
                pt = bll.GetOne(pid);
            }
            //上传图片
            string imageUrl = null;
            string s = FileUpload1.FileName;
            if (FileUpload1.HasFile)
            {
                Bitmap b = new Bitmap(FileUpload1.PostedFile.InputStream, false);
                string fileName = Guid.NewGuid().ToString();
                string rootPath = System.Configuration.ConfigurationManager.AppSettings["ImageManageFile"] + DateTime.Now.Year + "/" + DateTime.Now.Month + "/";
                string rootUrl = System.Configuration.ConfigurationManager.AppSettings["ImageManageUrl"] + DateTime.Now.Year + "/" + DateTime.Now.Month + "/";
                string path1 = rootPath + fileName + ".jpg";
                string url1 = rootUrl + fileName + ".jpg";
                //原始图片
                var data1 = CommTools.KiResizeImage(b, b.Width, b.Height);
                string msg = "";
                FileDeliver.StartTranCommand(data1, path1, out msg);

                if (string.IsNullOrEmpty(msg))
                    imageUrl = url1;
                pt.Ppicture = imageUrl;
            }
            if (ddlPid.SelectedValue == "")
            {
                ClientScript.RegisterClientScriptBlock(GetType(), "aa", "alert('请选择类型！');", true);
                return;
            }
            else
                pt.Padr = ddlPid.SelectedValue;

            string sort = txtPX.Text.ToString();
            try
            {
                int sortnum = int.Parse(sort);
                pt.SortNum = sortnum;
            }
            catch
            {
                ClientScript.RegisterClientScriptBlock(GetType(), "aa", "alert('排序只能输入数字！');", true);
                return;
            }
            

            pt.Pdes = txtContent.Text.ToString();
            pt.Pemail = txtEMail.Text.ToString();
            pt.Pname = txtTitle.Text.ToString();
            pt.Pphone = txtPhone.Text.ToString();
            pt.Purl = txtOutsideUrl.Text.ToString();
            pt.Status = Request["aa"] == "1" ? true : false;
            pt.CreateTime = pid == 0 ? DateTime.Now : DateTime.Parse(txtTime.Text); 
            
            if (pid > 0)
            {
                if (bll.UpdatePartner(pt) > 0)
                    ClientScript.RegisterStartupScript(GetType(), "aa", "alert('修改成功');document.location='Default.aspx?page=" + Request["page"] + "'", true);
                else
                    ClientScript.RegisterClientScriptBlock(GetType(), "aa", "alert('修改失败,请重试');", true);
            }
            else
            {
                if (bll.AddPartner(pt) > 0)
                    ClientScript.RegisterStartupScript(GetType(), "aa", "alert('添加成功');document.location='default.aspx'", true);
                else
                    ClientScript.RegisterClientScriptBlock(GetType(), "aa", "alert('添加失败,请重试');", true);
            }
        }
        catch (Exception ex)
        {
            ClientScript.RegisterClientScriptBlock(GetType(), "aa", "alert('添加失败,请重试');", true);   
        }
    }



    #region 替换危险Sql字符,不含特殊符号的值域
    /// <summary>
    /// 替换危险Sql字符,不含特殊符号的值域
    /// </summary>
    /// <param name="inputString">要替换的字符</param>
    /// <returns></returns>
    public string replaceStr(string inputString)
    {
        string replaceIn = "dynsrc|exp|import|behavior|style|iframe|meta|framset|object|embed|eval|adw|ad4|redirect|<?|<xml|<?xml|echo|cmd=|;//|document.write|&lt;|%3C|\\x|\\u|}|%|<|>|'|*|\"|;|:|(|)|#|&|@|create|drop|and|abs|unicode|cmdshel|db_name|net user|exec|insert|xp_cmdshell|sysobjects|select|delete|update|count|chr|asc|mid|master|net localgroup|truncate|char|declare|col_name|object_id|xtype|where|nchar|script";
        string[] ArrayReplaceIn = replaceIn.Split(char.Parse("|"));
        int i;
        for (i = 0; i < ArrayReplaceIn.Length; i++)
        {
            try
            {
                System.Text.RegularExpressions.Regex _tempRegex = new System.Text.RegularExpressions.Regex(@ArrayReplaceIn[i].ToString(), RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
                inputString = _tempRegex.Replace(inputString.Trim(), "");
            }
            catch { }
        }
        return inputString;
    }
    #endregion
}